<!--
  智慧社区管理系统 - 支付记录列表页面
  @author Wu.Liang
  @date 2025-06-26
  @version 3.0 - 根据系统设计调整方案重构，统一支付接口
-->
<template>
  <div class="payment-list-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2 class="page-title">支付记录管理</h2>
      <div class="page-actions">
        <el-button type="primary" @click="handleCreatePayment" :loading="creating">
          <el-icon><Plus /></el-icon>
          新建支付
        </el-button>
        <el-button type="success" @click="handleBatchRefund" :loading="refunding">
          <el-icon><RefreshLeft /></el-icon>
          批量退款
        </el-button>
        <el-button type="warning" @click="handleExport">
          <el-icon><Download /></el-icon>
          导出数据
        </el-button>
      </div>
    </div>

    <!-- 搜索表单 -->
    <el-card class="search-card" shadow="never">
      <el-form :model="searchForm" :inline="true" @submit.prevent="handleSearch">
        <el-form-item label="社区">
          <el-select
            v-model="searchForm.communityId"
            placeholder="请选择社区"
            clearable
            style="width: 200px"
          >
            <el-option
              v-for="item in communityList"
              :key="item.id"
              :label="item.name"
              :value="item.id || 0"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="支付方式">
          <el-select
            v-model="searchForm.paymentMethod"
            placeholder="请选择支付方式"
            clearable
            style="width: 150px"
          >
            <el-option label="微信支付" :value="1" />
            <el-option label="支付宝" :value="2" />
            <el-option label="银行卡" :value="3" />
            <el-option label="现金" :value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="支付状态">
          <el-select
            v-model="searchForm.paymentStatus"
            placeholder="请选择状态"
            clearable
            style="width: 150px"
          >
            <el-option label="待支付" :value="1" />
            <el-option label="支付中" :value="2" />
            <el-option label="支付成功" :value="3" />
            <el-option label="支付失败" :value="4" />
            <el-option label="已退款" :value="5" />
          </el-select>
        </el-form-item>
        <el-form-item label="业务类型">
          <el-select
            v-model="searchForm.businessType"
            placeholder="请选择业务类型"
            clearable
            style="width: 150px"
          >
            <el-option label="物业费" :value="1" />
            <el-option label="停车费" :value="2" />
            <el-option label="水电费" :value="3" />
            <el-option label="其他" :value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            @change="handleDateRangeChange"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item label="关键词">
          <el-input
            v-model="searchForm.keyword"
            placeholder="订单号/用户名/描述"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :loading="loading">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card" shadow="never">
      <div class="table-header">
        <div class="table-title">
          <span>支付记录列表</span>
          <el-tag :type="getTagType('info')" class="count-tag">共 {{ total }} 条记录</el-tag>
        </div>
        <div class="table-actions">
          <el-button
            type="danger"
            :disabled="!selectedRows.length"
            @click="handleBatchDelete"
          >
            批量删除
          </el-button>
        </div>
      </div>

      <el-table
        v-loading="loading"
        :data="tableData"
        @selection-change="handleSelectionChange"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="orderNo" label="订单号" width="180" />
        <el-table-column prop="userName" label="用户" width="100" />
        <el-table-column prop="communityName" label="社区" width="120" />
        <el-table-column prop="amount" label="支付金额" width="120">
          <template #default="{ row }">
            <span class="amount">¥{{ row.formattedAmount }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="paymentMethod" label="支付方式" width="120">
          <template #default="{ row }">
            <el-tag :type="getTagType(getPaymentMethodTagType(row.paymentMethod))">
              <el-icon v-if="row.paymentMethodIcon" class="payment-icon">
                <component :is="row.paymentMethodIcon" />
              </el-icon>
              {{ row.paymentMethodName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="paymentStatus" label="支付状态" width="120">
          <template #default="{ row }">
            <el-tag :type="getTagType(getStatusTagType(row.paymentStatus))" :effect="getStatusEffect(row.paymentStatus)">
              {{ row.paymentStatusName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="businessType" label="业务类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getTagType(getBusinessTypeTagType(row.businessType))">
              {{ row.businessTypeName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="paymentTime" label="支付时间" width="160">
          <template #default="{ row }">
            <span v-if="row.paymentTime">{{ formatDateTime(row.paymentTime) }}</span>
            <span v-else class="text-muted">未支付</span>
          </template>
        </el-table-column>
        <el-table-column prop="refundAmount" label="退款金额" width="120">
          <template #default="{ row }">
            <span v-if="row.refundAmount" class="refund-amount">
              ¥{{ row.formattedRefundAmount }}
            </span>
            <span v-else class="text-muted">-</span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="160" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              @click="handleViewDetail(row)"
            >
              详情
            </el-button>
            <el-button
              type="success"
              size="small"
              @click="handleRefund(row)"
              :disabled="!row.canRefund || row.isRefunded"
            >
              退款
            </el-button>
            <el-button
              type="warning"
              size="small"
              @click="handleCancel(row)"
              :disabled="row.paymentStatus !== 1"
            >
              取消
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页器 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新建支付弹窗 -->
    <PaymentFormDialog
      v-model="formDialogVisible"
      :loading="creating"
      @confirm="handleCreateConfirm"
    />

    <!-- 支付详情弹窗 -->
    <PaymentDetailDialog
      v-model="detailDialogVisible"
      :payment-data="currentPayment"
      @refund="handleRefund"
      @cancel="handleCancel"
    />

    <!-- 退款弹窗 -->
    <RefundDialog
      v-model="refundDialogVisible"
      :payment-data="currentPayment"
      :loading="refunding"
      @confirm="handleRefundConfirm"
    />

    <!-- 批量退款弹窗 -->
    <BatchRefundDialog
      v-model="batchRefundDialogVisible"
      :selected-rows="selectedRows"
      :loading="refunding"
      @confirm="handleBatchRefundConfirm"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessageBox } from 'element-plus'
import { showSuccess, showError, showWarning } from '@/utils/message'
import { 
  Plus, 
  RefreshLeft, 
  Download, 
  Search, 
  Refresh
} from '@element-plus/icons-vue'
import type { PaymentVO, PaymentQueryParams } from './types/payment'
import { paymentApi } from '@/api/payment'
import { commonApi } from '@/api/property'
import PaymentFormDialog from './components/PaymentFormDialog.vue'
import PaymentDetailDialog from './components/PaymentDetailDialog.vue'
import RefundDialog from './components/RefundDialog.vue'
import BatchRefundDialog from './components/BatchRefundDialog.vue'
import { getTagType } from '@/utils/message'

// 作者: Wu.Liang

// 响应式数据
const loading = ref(false)
const creating = ref(false)
const refunding = ref(false)

// 表格数据
const tableData = ref<PaymentVO[]>([])
const selectedRows = ref<PaymentVO[]>([])
const total = ref(0)

// 分页数据
const pagination = reactive({
  current: 1,
  size: 20
})

// 搜索表单 - 修复Element Plus警告
const searchForm = reactive<PaymentQueryParams>({
  communityId: null,
  paymentMethod: null,
  paymentStatus: null,
  businessType: null,
  startDate: null,
  endDate: null,
  keyword: ''
})

// 日期范围
const dateRange = ref<[string, string] | null>(null)

// 下拉选项数据
const communityList = ref<any[]>([])

// 弹窗控制
const formDialogVisible = ref(false)
const detailDialogVisible = ref(false)
const refundDialogVisible = ref(false)
const batchRefundDialogVisible = ref(false)

// 当前操作的支付
const currentPayment = ref<PaymentVO | null>(null)

// 计算属性
const queryParams = computed(() => ({
  ...searchForm,
  current: pagination.current,
  size: pagination.size
}))

// 生命周期
onMounted(() => {
  loadData()
  loadCommunityList()
})

// 加载数据 - 使用静态数据模拟
const loadData = async () => {
  try {
    loading.value = true
    
    // 模拟API延迟
    await new Promise(resolve => setTimeout(resolve, 500))
    
    // 静态数据模拟
    const mockData = {
      records: [
        {
          id: 1,
          orderNo: 'PAY202501010001',
          userId: 1,
          userName: '张先生',
          communityId: 1,
          communityName: '阳光花园',
          amount: 1200.00,
          formattedAmount: '1,200.00',
          paymentMethod: 1,
          paymentMethodName: '微信支付',
          paymentMethodIcon: 'Wechat',
          paymentStatus: 3,
          paymentStatusName: '支付成功',
          businessType: 1,
          businessTypeName: '物业费',
          businessOrderNo: 'PROP202501010001',
          description: '2025年1月物业费',
          transactionId: 'wx_202501010001',
          createTime: '2025-01-01 09:00:00',
          payTime: '2025-01-01 09:05:00',
          canRefund: true,
          isRefunded: false
        },
        {
          id: 2,
          orderNo: 'PAY202501010002',
          userId: 2,
          userName: '李女士',
          communityId: 1,
          communityName: '阳光花园',
          amount: 50.00,
          formattedAmount: '50.00',
          paymentMethod: 2,
          paymentMethodName: '支付宝',
          paymentMethodIcon: 'Alipay',
          paymentStatus: 3,
          paymentStatusName: '支付成功',
          businessType: 2,
          businessTypeName: '停车费',
          businessOrderNo: 'PARK202501010001',
          description: '地下车库月租费',
          transactionId: 'alipay_202501010002',
          createTime: '2025-01-01 10:00:00',
          payTime: '2025-01-01 10:02:00',
          canRefund: true,
          isRefunded: false
        },
        {
          id: 3,
          orderNo: 'PAY202501010003',
          userId: 3,
          userName: '王先生',
          communityId: 2,
          communityName: '绿城小区',
          amount: 300.00,
          formattedAmount: '300.00',
          paymentMethod: 3,
          paymentMethodName: '银行卡',
          paymentMethodIcon: 'CreditCard',
          paymentStatus: 2,
          paymentStatusName: '支付中',
          businessType: 3,
          businessTypeName: '水电费',
          businessOrderNo: 'UTIL202501010001',
          description: '2025年1月水电费',
          transactionId: null,
          createTime: '2025-01-01 11:00:00',
          payTime: null,
          canRefund: false,
          isRefunded: false
        },
        {
          id: 4,
          orderNo: 'PAY202501010004',
          userId: 4,
          userName: '赵女士',
          communityId: 1,
          communityName: '阳光花园',
          amount: 80.00,
          formattedAmount: '80.00',
          paymentMethod: 1,
          paymentMethodName: '微信支付',
          paymentMethodIcon: 'Wechat',
          paymentStatus: 5,
          paymentStatusName: '已退款',
          businessType: 4,
          businessTypeName: '其他',
          businessOrderNo: 'OTHER202501010001',
          description: '维修服务费',
          transactionId: 'wx_202501010004',
          createTime: '2025-01-01 12:00:00',
          payTime: '2025-01-01 12:05:00',
          canRefund: false,
          isRefunded: true
        }
      ],
      total: 4,
      size: 20,
      current: 1,
      pages: 1
    }
    
    tableData.value = mockData.records
    total.value = mockData.total
    
  } catch (error) {
    console.error('加载支付记录失败:', error)
    showError('加载数据失败')
  } finally {
    loading.value = false
  }
}

// 加载社区列表 - 使用静态数据
const loadCommunityList = async () => {
  try {
    // 静态数据模拟
    communityList.value = [
      { id: 1, name: '阳光花园' },
      { id: 2, name: '绿城小区' },
      { id: 3, name: '金桂苑' },
      { id: 4, name: '银桂苑' }
    ]
  } catch (error) {
    console.error('加载社区列表失败:', error)
  }
}

// 事件处理
const handleSearch = () => {
  pagination.current = 1
  loadData()
}

const handleReset = () => {
  Object.assign(searchForm, {
    communityId: null,
    paymentMethod: null,
    paymentStatus: null,
    businessType: null,
    startDate: null,
    endDate: null,
    keyword: ''
  })
  dateRange.value = null
  pagination.current = 1
  loadData()
}

const handleDateRangeChange = (range: [string, string] | null) => {
  if (range) {
    searchForm.startDate = range[0]
    searchForm.endDate = range[1]
  } else {
    searchForm.startDate = null
    searchForm.endDate = null
  }
}

const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.current = 1
  loadData()
}

const handleCurrentChange = (current: number) => {
  pagination.current = current
  loadData()
}

const handleSelectionChange = (rows: PaymentVO[]) => {
  selectedRows.value = rows
}

// 新建支付
const handleCreatePayment = () => {
  formDialogVisible.value = true
}

const handleCreateConfirm = async (data: any) => {
  try {
    creating.value = true
    const response = await paymentApi.createPayment(data)
    if (response.data && response.code === 200) {
      showSuccess('支付订单创建成功')
      formDialogVisible.value = false
      loadData()
    } else {
      showError(response.message || '创建支付订单失败')
    }
  } catch (error) {
    console.error('创建支付订单失败:', error)
    showError('创建支付订单失败')
  } finally {
    creating.value = false
  }
}

// 查看详情
const handleViewDetail = (row: PaymentVO) => {
  currentPayment.value = row
  detailDialogVisible.value = true
}

// 退款
const handleRefund = (row: PaymentVO) => {
  currentPayment.value = row
  refundDialogVisible.value = true
}

const handleRefundConfirm = async (data: any) => {
  try {
    refunding.value = true
    const response = await paymentApi.applyRefund({
      paymentId: currentPayment.value!.id,
      refundAmount: data.refundAmount,
      refundReason: data.refundReason,
      remark: data.remark
    })
    if (response.data && response.code === 200) {
      showSuccess('退款申请提交成功')
      refundDialogVisible.value = false
      loadData()
    } else {
      showError(response.message || '申请退款失败')
    }
  } catch (error) {
    console.error('申请退款失败:', error)
    showError('申请退款失败')
  } finally {
    refunding.value = false
  }
}

// 取消支付
const handleCancel = async (row: PaymentVO) => {
  try {
    await ElMessageBox.confirm(
      '确定要取消这个支付订单吗？',
      '取消确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const response = await paymentApi.cancelPayment(row.id)
    if (response.data && response.code === 200) {
      showSuccess('支付订单取消成功')
      loadData()
    } else {
      showError(response.message || '取消支付订单失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消支付订单失败:', error)
      showError('取消支付订单失败')
    }
  }
}

// 批量退款
const handleBatchRefund = () => {
  if (selectedRows.value.length === 0) {
    showWarning('请选择要退款的支付记录')
    return
  }
  batchRefundDialogVisible.value = true
}

const handleBatchRefundConfirm = async (data: any) => {
  try {
    refunding.value = true
    // 这里需要后端提供批量退款接口
    showWarning('批量退款功能待实现')
    batchRefundDialogVisible.value = false
  } catch (error) {
    console.error('批量退款失败:', error)
    showError('批量退款失败')
  } finally {
    refunding.value = false
  }
}

// 删除
const handleDelete = async (row: PaymentVO) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这条支付记录吗？删除后无法恢复。',
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const response = await paymentApi.deletePayment(row.id)
    if (response.data && response.code === 200) {
      showSuccess('删除成功')
      loadData()
    } else {
      showError(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      showError('删除失败')
    }
  }
}

// 批量删除
const handleBatchDelete = async () => {
  if (selectedRows.value.length === 0) {
    showWarning('请选择要删除的支付记录')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedRows.value.length} 条支付记录吗？删除后无法恢复。`,
      '批量删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const paymentIds = selectedRows.value.map(row => row.id)
    const response = await paymentApi.batchDeletePayments(paymentIds)
    if (response.data && response.code === 200) {
      showSuccess(`成功删除 ${response.data.successCount} 条记录`)
      loadData()
    } else {
      showError(response.message || '批量删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      showError('批量删除失败')
    }
  }
}

// 导出
const handleExport = async () => {
  try {
    const response = await paymentApi.exportPayments(queryParams.value)
    const blob = new Blob([response], { type: 'application/vnd.ms-excel' })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `支付记录_${new Date().toISOString().split('T')[0]}.xlsx`
    link.click()
    window.URL.revokeObjectURL(url)
    showSuccess('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    showError('导出失败')
  }
}

// 工具方法
const getPaymentMethodTagType = (paymentMethod: number) => {
  const typeMap = {
    1: 'success',
    2: 'primary',
    3: 'warning',
    4: 'info'
  }
  return typeMap[paymentMethod as keyof typeof typeMap] || 'info'
}

const getStatusTagType = (status: number) => {
  const typeMap = {
    1: 'warning',
    2: 'primary',
    3: 'success',
    4: 'danger',
    5: 'info'
  }
  return typeMap[status as keyof typeof typeMap] || 'info'
}

const getStatusEffect = (status: number) => {
  return status === 4 ? 'dark' : 'light'
}

const getBusinessTypeTagType = (businessType: number) => {
  const typeMap = {
    1: 'primary',
    2: 'success',
    3: 'warning',
    4: 'info'
  }
  return typeMap[businessType as keyof typeof typeMap] || 'info'
}

const formatDateTime = (dateTime: string) => {
  if (!dateTime) return ''
  return new Date(dateTime).toLocaleString()
}
</script>

<style scoped>
.payment-list-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  margin: 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.page-actions {
  display: flex;
  gap: 10px;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.table-title {
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 16px;
  font-weight: 600;
}

.count-tag {
  font-size: 12px;
}

.table-actions {
  display: flex;
  gap: 10px;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.amount {
  font-weight: 600;
  color: #67c23a;
}

.refund-amount {
  font-weight: 600;
  color: #f56c6c;
}

.text-muted {
  color: #909399;
  font-size: 12px;
}

.payment-icon {
  margin-right: 4px;
}
</style> 